<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  User,
  SwitchButton,
  ChatDotRound,
  MessageBox,
  Share
} from '@element-plus/icons-vue'
import LoginModal from './components/LoginModal.vue'
import RegisterModal from './components/RegisterModal.vue'
import { authUtils } from './utils/auth'

const router = useRouter()
const route = useRoute()

const activeIndex = ref('/')

// 登录状态管理
const isLoggedIn = ref(false)
const currentUser = ref(null)

// 弹窗状态管理
const showLoginModal = ref(false)
const showRegisterModal = ref(false)

// 计算属性：用户头像
const userAvatar = computed(() => {
  return currentUser.value?.avatar || 'https://picsum.photos/100/100?random=120'
})

// 计算属性：用户昵称或用户名
const displayName = computed(() => {
  if (!currentUser.value) return 'xiaozhuang'
  return (
    currentUser.value.nickname || currentUser.value.username || 'xiaozhuang'
  )
})

// 获取所有需要在导航栏显示的路由
const mainNavItems = computed(() => {
  return router.options.routes
    .filter((route) => route.meta?.showInNav)
    .map((route) => ({
      path: route.path,
      title: route.meta.title
    }))
})

const handleSelect = (key) => {
  router.push(key)
}

// 显示登录弹窗
const showLogin = () => {
  showLoginModal.value = true
}

// 显示注册弹窗
const showRegister = () => {
  showRegisterModal.value = true
}

// 登录成功处理
const handleLoginSuccess = (userData) => {
  isLoggedIn.value = true
  currentUser.value = userData
  showLoginModal.value = false

  // 登录成功后跳转到之前保存的路径
  const redirectPath = sessionStorage.getItem('redirectAfterLogin')
  if (redirectPath) {
    sessionStorage.removeItem('redirectAfterLogin')
    router.push(redirectPath)
  }
}

// 注册成功处理
const handleRegisterSuccess = (userData) => {
  showRegisterModal.value = false
  // 注册成功后自动显示登录弹窗
  showLoginModal.value = true
}

// 退出登录
const handleLogout = () => {
  isLoggedIn.value = false
  currentUser.value = null
  // 清除localStorage中的登录信息
  authUtils.clearAuth()
  console.log('已退出登录')
}

// 切换弹窗显示
const switchToLogin = () => {
  showRegisterModal.value = false
  showLoginModal.value = true
}

const switchToRegister = () => {
  showLoginModal.value = false
  showRegisterModal.value = true
}

// 从localStorage恢复登录状态
const restoreLoginState = () => {
  if (authUtils.isLoggedIn()) {
    const user = authUtils.getCurrentUser()
    isLoggedIn.value = true
    currentUser.value = user
    console.log('已恢复登录状态:', user)
  } else {
    // 清除无效的localStorage数据
    authUtils.clearAuth()
  }
}

// 监听用户信息更新事件
const handleUserInfoUpdate = () => {
  if (authUtils.isLoggedIn()) {
    const user = authUtils.getCurrentUser()
    currentUser.value = user
    console.log('用户信息已更新:', user)
  }
}

// 监听路由守卫触发的登录弹窗事件
const handleShowLoginModal = (event) => {
  const { message, redirectPath } = event.detail || {}
  if (message) {
    // 显示提示消息
    import('element-plus').then(({ ElMessage }) => {
      ElMessage.warning(message)
    })
  }
  // 显示登录弹窗
  showLoginModal.value = true

  // 保存重定向路径，登录成功后跳转
  if (redirectPath) {
    sessionStorage.setItem('redirectAfterLogin', redirectPath)
  }
}

// 组件挂载时恢复登录状态
onMounted(() => {
  restoreLoginState()
  // 监听用户信息更新事件
  window.addEventListener('userInfoUpdated', handleUserInfoUpdate)
  // 监听路由守卫触发的登录弹窗事件
  window.addEventListener('show-login-modal', handleShowLoginModal)
})

// 组件卸载时清理事件监听
onUnmounted(() => {
  window.removeEventListener('userInfoUpdated', handleUserInfoUpdate)
  window.removeEventListener('show-login-modal', handleShowLoginModal)
})
</script>

<template>
  <div class="app-container">
    <el-container>
      <el-header>
        <div class="header-container">
          <div class="logo" @click="router.push('/')">
            <span class="logo-text">Trave旅行日记</span>
          </div>
          <el-menu
            :default-active="route.path"
            class="main-menu"
            mode="horizontal"
            @select="handleSelect"
            background-color="#ffffff"
            text-color="#333"
            active-text-color="#409EFF"
          >
            <el-menu-item
              v-for="item in mainNavItems"
              :key="item.path"
              :index="item.path"
            >
              {{ item.title }}
            </el-menu-item>
          </el-menu>
          <div class="user-actions">
            <!-- 未登录状态 -->
            <div v-if="!isLoggedIn" class="login-section">
              <el-button type="primary" @click="showLogin" class="login-btn">
                登录
              </el-button>
            </div>

            <!-- 已登录状态 -->
            <el-dropdown v-else trigger="click">
              <div class="user-avatar">
                <el-avatar :src="userAvatar" size="small"></el-avatar>
                <span class="username">{{ displayName }}</span>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="router.push('/profile')">
                    <el-icon><User /></el-icon> 个人中心
                  </el-dropdown-item>
                  <el-dropdown-item divided @click="handleLogout">
                    <el-icon><SwitchButton /></el-icon> 退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-header>
      <el-main
        :class="{
          'no-padding': route.path === '/ai-assistant' || route.path === '/'
        }"
      >
        <router-view v-slot="{ Component, route }">
          <component :is="Component" :key="route.fullPath" />
        </router-view>
      </el-main>
      <el-footer v-if="route.path !== '/ai-assistant'" class="modern-footer">
        <div class="footer-content">
          <div class="footer-top">
            <div class="footer-brand">
              <h3 class="footer-logo">Trave旅行日记</h3>
              <p class="footer-slogan">探索世界，记录美好</p>
              <div class="footer-social">
                <a href="#" class="social-icon">
                  <el-icon><ChatDotRound /></el-icon>
                </a>
                <a href="#" class="social-icon">
                  <el-icon><MessageBox /></el-icon>
                </a>
                <a href="#" class="social-icon">
                  <el-icon><Share /></el-icon>
                </a>
              </div>
            </div>

            <div class="footer-links-group">
              <div class="footer-column">
                <h4>探索</h4>
                <a href="#" @click.prevent="router.push('/city')">热门城市</a>
                <a href="#" @click.prevent="router.push('/travel-note')"
                  >精选游记</a
                >
                <a href="#" @click.prevent="router.push('/community')"
                  >社区广场</a
                >
              </div>

              <div class="footer-column">
                <h4>服务</h4>
                <a href="#" @click.prevent="router.push('/travel-plan')"
                  >旅行计划</a
                >
                <a href="#" @click.prevent="router.push('/ai-assistant')"
                  >AI助手</a
                >
                <a href="#" @click.prevent="router.push('/budget')">预算管理</a>
              </div>

              <div class="footer-column">
                <h4>关于</h4>
                <a href="#">关于我们</a>
                <a href="#">联系我们</a>
                <a href="#">加入我们</a>
              </div>

              <div class="footer-column">
                <h4>法律</h4>
                <a href="#">隐私政策</a>
                <a href="#">服务条款</a>
                <a href="#">用户协议</a>
              </div>
            </div>
          </div>

          <div class="footer-bottom">
            <p class="copyright">© 2025 Trave旅行日记. All rights reserved.</p>
            <div class="footer-meta">
              <span>京ICP备xxxxxxxx号</span>
              <span>·</span>
              <span>Made with ❤️ in China</span>
            </div>
          </div>
        </div>
      </el-footer>
    </el-container>

    <!-- 登录弹窗 -->
    <LoginModal
      :visible="showLoginModal"
      @update:visible="showLoginModal = $event"
      @login-success="handleLoginSuccess"
      @show-register="switchToRegister"
    />

    <!-- 注册弹窗 -->
    <RegisterModal
      :visible="showRegisterModal"
      @update:visible="showRegisterModal = $event"
      @register-success="handleRegisterSuccess"
      @show-login="switchToLogin"
    />
  </div>
</template>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html,
body {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
  overflow-x: hidden;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

#app {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}

.app-container {
  min-height: 100vh;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.el-container {
  min-height: 100vh;
}

.el-header {
  padding: 0;
  height: auto !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
  background-color: #fff;
}

.header-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 60px;
}

.logo {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.logo-text {
  font-size: 20px;
  font-weight: bold;
  color: #409eff;
}

.main-menu {
  flex: 1;
  justify-content: center;
  border-bottom: none;
}

.user-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.login-section {
  display: flex;
  align-items: center;
}

.login-btn {
  background: linear-gradient(135deg, #ff6b6b 0%, #ff8e8e 100%);
  border: none;
  border-radius: 8px;
  padding: 8px 20px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.login-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(255, 107, 107, 0.4);
}

.user-avatar {
  display: flex;
  align-items: center;
  cursor: pointer;
  gap: 8px;
}

.username {
  font-size: 14px;
  color: #606266;
}

.el-main {
  padding: 20px;
  background-color: #f5f7fa;
}

.no-padding {
  padding: 0;
}

.el-footer {
  background-color: #f5f7fa;
  padding: 20px;
  border-top: 1px solid #e4e7ed;
}

.footer-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.footer-logo {
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
}

.footer-links {
  display: flex;
  gap: 20px;
}

.footer-links a {
  color: #606266;
  text-decoration: none;
}

.footer-links a:hover {
  color: #409eff;
}

.footer-copyright {
  color: #909399;
  font-size: 12px;
}

@media (max-width: 768px) {
  .header-container {
    flex-direction: column;
    height: auto;
    padding: 10px;
  }

  .logo {
    margin-bottom: 10px;
  }

  .main-menu {
    width: 100%;
    margin-bottom: 10px;
  }

  .user-actions {
    width: 100%;
    justify-content: flex-end;
  }
}

.header-container {
  height: 60px;
  display: flex;
  align-items: center;
  padding: 0 20px;
}

.logo {
  cursor: pointer;
  margin-right: 30px;
}

.logo-text {
  font-size: 22px;
  font-weight: bold;
  background: linear-gradient(45deg, #42b883, #35495e);
  background-clip: text;
  -webkit-background-clip: text;
  color: transparent;
}

.main-menu {
  flex: 1;
  border-bottom: none;
}

.user-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.el-main {
  padding: 20px;
  background-color: #f5f7fa;
}

.el-main.no-padding {
  padding: 0;
  overflow: hidden;
}

.modern-footer {
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
  color: #e4e4e4;
  padding: 0;
  height: auto !important;
  border-top: 1px solid rgba(100, 255, 218, 0.1);
}

.footer-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 60px 40px 30px;
}

.footer-top {
  display: grid;
  grid-template-columns: 2fr 3fr;
  gap: 60px;
  margin-bottom: 40px;
  padding-bottom: 40px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.footer-brand {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.footer-logo {
  font-size: 28px;
  font-weight: 700;
  background: linear-gradient(135deg, #64ffda 0%, #1de9b6 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin: 0;
}

.footer-slogan {
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
  margin: 0;
  letter-spacing: 0.5px;
}

.footer-social {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-top: 8px;
}

.social-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: rgba(100, 255, 218, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #64ffda;
  font-size: 18px;
  transition: all 0.3s ease;
  border: 1px solid rgba(100, 255, 218, 0.2);
}

.social-icon:hover {
  background: rgba(100, 255, 218, 0.2);
  transform: translateY(-3px);
  box-shadow: 0 8px 20px rgba(100, 255, 218, 0.2);
}

.footer-links-group {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 30px;
}

.footer-column {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.footer-column h4 {
  color: #fff;
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 8px 0;
  letter-spacing: 0.5px;
}

.footer-column a {
  color: rgba(255, 255, 255, 0.7);
  text-decoration: none;
  font-size: 14px;
  transition: all 0.3s ease;
  position: relative;
  padding-left: 0;
}

.footer-column a::before {
  content: '';
  position: absolute;
  left: 0;
  bottom: -2px;
  width: 0;
  height: 2px;
  background: linear-gradient(90deg, #64ffda, #1de9b6);
  transition: width 0.3s ease;
}

.footer-column a:hover {
  color: #64ffda;
  padding-left: 8px;
}

.footer-column a:hover::before {
  width: 20px;
}

.footer-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20px;
}

.copyright {
  margin: 0;
  color: rgba(255, 255, 255, 0.5);
  font-size: 14px;
}

.footer-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  color: rgba(255, 255, 255, 0.5);
  font-size: 13px;
}

.footer-meta span {
  display: inline-block;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .footer-content {
    padding: 40px 20px 20px;
  }

  .footer-top {
    grid-template-columns: 1fr;
    gap: 40px;
  }

  .footer-links-group {
    grid-template-columns: repeat(2, 1fr);
    gap: 24px;
  }

  .footer-bottom {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .footer-meta {
    flex-wrap: wrap;
    justify-content: center;
  }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
